import { useState, useEffect } from 'react'
import { useSelector } from 'react-redux'
import { message } from 'antd'
import to from 'await-to-js'
import _ from 'lodash'

import { useAppDispatch } from '@/store'
import { signsUpdateTime } from '@/api/sign'
import { signAction, updataSignData } from '@/store/modules/signStore'
import { useDateTimer } from '@/hooks/dataTimeHook'
import { toZero } from '@/utils/common'
import { DescriptionsKey } from './enums'

import type { RootState } from '@/store'
import type { Dayjs } from 'dayjs'
import type { ResponseSignsTime } from '@/api/sign/type'
import type { TypeDetailState,TypeDescriptionsData } from './type'

const initDetailState: TypeDetailState = {
    type: 'success',
    text: '正常'
}

//  考勤状态收集器
const initDescriptionsData: TypeDescriptionsData = {
    normal: 0, // 正常出勤
    absent: 0, // 旷工
    miss: 0,// 漏打卡
    late: 0, // 迟到
    early: 0, // 早退
    lateAndEarly: 0 //迟到并早退
}

export const useCalendar = () => {

    const dispatch = useAppDispatch()

    const userInfo = useSelector((state: RootState) => state.userStore.infos)
    const signData = useSelector((state: RootState) => state.signStore.signData)

    const { dateMonth } = useDateTimer()

    const [ month, setMonth ] = useState(dateMonth)
    const [ detailState, setDetailState ] = useState(initDetailState)

    const [ descriptionsData, setDescriptionsData ] = useState(initDescriptionsData)

    const monthOptions: { value: number, label: string }[] = []
    for (let i = 1; i <= 12; i += 1) {
        monthOptions.push({
            value: i,
            label: `${i}月`
        })
    }

    //  用户点击月份 日历变化
    const handleCalendarSelect = (val: number, dayJs: Dayjs, cb: any) => {
        setMonth(val)
        cb(dayJs.clone().month(val))
    }

    //  获取打卡数据
    useEffect(() => {
        const getSignData = async () => {
            const { payload } = await dispatch(signAction(userInfo._id))
            const { errcode, infos } = payload as ResponseSignsTime
            if (errcode !== 0) return false
            dispatch(updataSignData(infos))
        }

        if (_.isEmpty(signData)) {
            getSignData()
        }

    }, [signData, userInfo._id])

    const dateCellRender = (val: Dayjs) => {

        const m = signData.time && signData.time[toZero(val.month() + 1)]
        const d = m && m[toZero(val.date())]

        return Array.isArray(d) ? d.join('-') : ''

    }

    //  点击签到
    const handlePutTimeBtb = async () => {
        const [ err, res ] = await to(signsUpdateTime({ userid: userInfo._id }))
        err && console.error(err)
        if (res?.errcode !== 0) return message.error(res?.errmsg)

        dispatch(updataSignData(res.infos))
    }

    useEffect(() => {
        if (signData.detail) {

            const m = toZero(month)
            const detailMonth = signData.detail[m]
            for (const item in detailMonth) {
                switch (detailMonth[item]) {
                    case DescriptionsKey.normal:
                        initDescriptionsData.normal++
                        break
                    case DescriptionsKey.absent:
                        initDescriptionsData.absent++
                        break
                    case DescriptionsKey.miss:
                        initDescriptionsData.miss++
                        break
                    case DescriptionsKey.late:
                        initDescriptionsData.late++
                        break
                    case DescriptionsKey.early:
                        initDescriptionsData.early++
                        break
                    case DescriptionsKey.lateAndEarly:
                        initDescriptionsData.lateAndEarly++
                        break
                }
            }

            setDescriptionsData(initDescriptionsData)

            //  计算考勤状态
            for (const item in descriptionsData) {
                if (item !== DescriptionsKey.normal && descriptionsData[item as keyof typeof descriptionsData] !== 0) {
                    initDetailState.type = 'error'
                    initDetailState.text = '异常'
                }
            }

            setDetailState(initDetailState)

        }

        return () => {
            // 更新前触发
            initDescriptionsData.normal = 0
            initDescriptionsData.absent = 0
            initDescriptionsData.miss = 0
            initDescriptionsData.late = 0
            initDescriptionsData.early = 0
            initDescriptionsData.lateAndEarly = 0
            setDescriptionsData(initDescriptionsData)
            setDetailState({
                type: 'success',
                text: '正常'
            })
        }
    }, [descriptionsData, month, signData.detail])


    return {
        detailState,
        descriptionsData,
        monthOptions,
        month,
        handleCalendarSelect,
        dateCellRender,
        handlePutTimeBtb
    }
}
